// pages/myCollect/myCollect.js
var app = getApp();
Page({

  data: {
    currentIndex: 0,
    coachList: [],
    coachListLen: 0,
    drivingSchoolList: [],
    drivingSchoolListLen: 0,
    articles: [],
    articlesLength: 0,
  },

  onLoad: function (options) {
    // console.log(app.globalData);
    const lng = app.globalData.userLocation.longitude;
    const lat = app.globalData.userLocation.latitude;
    // console.log(lng,lat);
    this.getCoachListPromise(lng,lat).then(res=>{
      // console.log(res);
      if(res.data.code == 0 && res.data.message == "成功"){
        const _t = [];
        for (let i of res.data.data) {
          let t = Object.assign({}, i); 
          t.special = (i.mark.split(',')).slice(0, 4);
          let distance = parseFloat(i.distance);
          if (distance >= 1000) {
            t.distance = (distance / 1000).toFixed(1) + 'km';
          } else {
            t.distance = distance + 'm';
          }
          t.score = t.score ? t.score.toFixed(1) : '0.0';
          _t.push(t);
        };
        this.setData({
          coachList: _t,
          coachListLen: _t.length,
        });
      }
    }).catch(err=>{
      console.warn(err);
    });
    this.getDrivingListPromise(lng,lat).then(res=>{
      // console.log(res.data.data.length);
      if(res.data.code == 0 && res.data.message == "成功"){
        const _t = [];
        for(let i of res.data.data){
          let t = Object.assign({},i);
          t.special = (i.mark.split(',')).slice(0, 2);
          let distance = parseFloat(i.distance);
          if(distance >= 1000){
            t.distance = (distance / 1000).toFixed(1) + 'km';
          }else{
            t.distance = distance + 'm';
          }
          _t.push(t);
        };
        // console.log(_t.length);
        this.setData({
          drivingSchoolList: _t,
          drivingSchoolListLen: _t.length,
        })
      }
    }).catch(err=>{
      console.warn(err);
    });
    this.getArticlePromise().then(res=>{
      // console.log(res);
      if(res.data.code == 0 && res.data.message == "成功"){
        let arr = res.data.data;
        let _arr = [];
        for(let i of arr){
          let o = Object.assign({},i);
          o.time1 = this.timestampToTime(i.createDate).split(' ')[0].split('-');
          o.time = o.time1[0] + '年' + o.time1[1] + '月' + o.time1[2] + '日';  
          console.info(o.time);
          _arr.push(o);
        }
        this.setData({
          articles: _arr,
          articlesLength: res.data.data.length,
        })
      }
    }).catch(err=>{
      console.warn(err);
    })
  },

  onReady: function () {

  },
  changeNav(e){
    if (e.detail.text == "教练") {
      this.setData({
        currentIndex: 0
      });
      
    } else if (e.detail.text == "驾校") {
      this.setData({
        currentIndex: 1
      })
    } else if (e.detail.text == "文章"){
      this.setData({
        currentIndex: 2
      })
    }
  },
  getCoachListPromise(_lng,_lat){
    return new Promise((resolve,reject)=>{
       wx.request({
         url: 'https://www.haitunxueche.com/student/index/listAttentionTeacher',
         data: {
           latitude: _lat,
           longitude: _lng,
         },
         header: {
           Authorization: getApp().globalData.login.token,
         },
         method: 'GET',
         dataType: 'json',
         success: (res) => {
           if(res.data.code == 0){
            let list = [];
            for(let i of res.data.data){
              let test;
              for(let j of list){
                if(i.id === j.id){
                  test = true;
                  break;
                }
              }
              if(!test){
                list.push(i);
              }
              res.data.data = list;
            }
            resolve(res);
           }
         },
         fail: (err)=>{

         },
         complete: (e)=>{

         }
       }) 
    })
  },
  getDrivingListPromise(_lng,_lat){
    return new Promise((resolve,reject)=>{
       wx.request({
         url: 'https://www.haitunxueche.com/student/index/listAttentionSchool',
         data: {
           latitude: _lat,
           longitude: _lng,
         },
         header: {
           Authorization: getApp().globalData.login.token,
         },
         method: 'GET',
         dataType: 'json',
         success: (res) => {
           resolve(res);
         },
         fail: (err)=>{
           reject(err);
         },
         complete: (e)=>{

         }
       }) 
    })
  },
  getArticlePromise(){
    return new Promise((resolve,reject)=>{
       wx.request({
         url: 'https://www.haitunxueche.com/student/index/listAttentionArticle',
         header: {
           Authorization: getApp().globalData.login.token,
         },
         method: 'GET',
         dataType: 'json',
         success: (res) => {
           resolve(res);
         },
         fail: (err)=>{
           reject(err);
         },
         complete: (e)=>{

         }
       }) 
    })
  },
  handleCoach(e){
    wx.navigateTo({
      url: '../coach/coach?tid=' + e.currentTarget.dataset.tid,
    })
  },
  handleSchool(e){
    // console.log(e);
    wx.navigateTo({
      url: '../drivingSchool/drivingSchool?tid=' + e.currentTarget.dataset.tid,
    })
  },
  readingFunc(e){
    // console.log(e);
    const str = e.currentTarget.dataset.id;
    const time = e.currentTarget.dataset.time;
    wx.navigateTo({
      url: '../articleReading/articleReading?id=' + str + '&time=' + time,
    })
  },
  timestampToTime(timestamp) {
    // var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() + ' ';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
    return Y + M + D + h + m + s;
  },
})